package com.mzj.saas.mservice.lockManager.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.DateUtils;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.StatusCode;
import com.mzj.saas.commons.enums.OSSUploadFileTypeEnum;
import com.mzj.saas.config.oss.OssConfig;
import com.mzj.saas.mservice.lockManager.entity.SmartLockBrand;
import com.mzj.saas.mservice.lockManager.repository.SmartLockBrandRepository;
import com.mzj.saas.mservice.lockManager.vo.LockBrandListVO;
import com.mzj.saas.mservice.lockManager.vo.LockBrandVO;
import com.mzj.saas.mservice.oss.service.OSSService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class LockBrandService {
    private static final Logger log = LoggerFactory.getLogger(LockBrandService.class);

    private static final String BRAND_ORDER = " ORDER BY b.create_time DESC";
    private static final String SQL_PAGE = " LIMIT ? OFFSET ?";
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SmartLockBrandRepository smartLockBrandRepository;
    @Autowired
    private OSSService ossService;
    @Autowired
    private OssConfig ossConfig;

    public ResultBean<ApiData<LockBrandListVO>> lockBrandList(String accessToken, Integer status, Integer pageNumber, Integer pageSize) {
        ResultBean<ApiData<LockBrandListVO>> resultBean = new ResultBean<>();
        resultBean.setCode("10000");
        resultBean.setMsg("10000");
        ApiData<LockBrandListVO> apiData = new ApiData<>();
        resultBean.setResultData(apiData);
        try {

            StringBuilder where = new StringBuilder();
            List<Object> args = new ArrayList<>();
            where.append(" where 1 = 1");
            where.append(" AND b.del_status = 1");

            if (status != null) {
                where.append(" AND b.`status` = ?");
                args.add(status);
            }

            // 总记录数
            Long total = jdbcTemplate.queryForObject("SELECT count(1) FROM `saas_smart_lock_brand` b" + where, args.toArray(), Long.class);
            if (total == 0) {
                return resultBean;
            }

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<LockBrandListVO> list = jdbcTemplate.query("SELECT b.id,b.name,b.logo_path AS logoPath,b.status,b.create_time as createTime FROM `saas_smart_lock_brand` b" + where + BRAND_ORDER + SQL_PAGE,
                    new BeanPropertyRowMapper<>(LockBrandListVO.class), args.toArray());

            for (LockBrandListVO vo : list) {
                vo.setCreateTime(DateUtils.format(vo.getCreateTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));
            }

            apiData.setData(list);
            apiData.setTotal(total);

            resultBean.setResultData(apiData);
        } catch (Exception e) {
            log.error("LockBrandService lockBrandList Exception = {}" + e.getMessage(), e);
            resultBean.setCode("10001");
            resultBean.setMsg("10001");
        }
        resultBean.setResultData(apiData);
        return resultBean;
    }

    public ResultBean<Object> saveBrand(String accessToken, String name, MultipartFile file) {
        try {
            if (StringUtils.isBlank(name)) {
                return ResultBean.failedResultOfParamWithMsg("品牌名称为空");
            }
            if (file == null) {
                return ResultBean.failedResultOfParamWithMsg("文件为空");
            }
            // 上传图片
            ResultBean<Object> objectResultBean = ossService.putFile(ossConfig.getOssBucketName(), file, OSSUploadFileTypeEnum.LOGO.toString());
            String code = objectResultBean.getCode();
            String msg = objectResultBean.getMsg();
            if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                return ResultBean.failedResultWithCodeAndMsg(code, msg);
            } else {
                String fileKey = objectResultBean.getResultData().toString();
                //String url = ossService.getOssFilePath(fileKey);

                SmartLockBrand smartLockBrand = new SmartLockBrand();
                smartLockBrand.setName(name);
                smartLockBrand.setLogoPath(fileKey);
                smartLockBrand.setApiUrl(fileKey);
                smartLockBrand.setStatus(1);//激活
                smartLockBrand.setDelStatus(1);//正常
                smartLockBrand.setRemoteUpgrade(0);
                smartLockBrand.setLowPowerSet(0);
                smartLockBrand.setVolumeSet(0);
                smartLockBrand.setStrangerOpenAlarm(0);
                smartLockBrand.setPickProofAlarm(0);
                smartLockBrand.setDuressAlarm(0);
                smartLockBrand.setFactoryReset(0);
                smartLockBrand.setFingerprintStatus(1);
                smartLockBrand.setBleStatus(1);
                smartLockBrand.setCreateTime(new Date());
                smartLockBrandRepository.save(smartLockBrand);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockBrandService saveBrand Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<LockBrandVO> findBrand(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("id为空");
            }

            Optional<SmartLockBrand> brandOpt = smartLockBrandRepository.findById(id);
            if (!brandOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁品牌不存在");
            }
            SmartLockBrand brand = brandOpt.get();
            LockBrandVO vo = new LockBrandVO();
            vo.setId(brand.getId());
            vo.setName(brand.getName());
            vo.setLogoPath(brand.getLogoPath());

            return ResultBean.successfulResult(vo);
        } catch (Exception e) {
            log.error("LockBrandService updateBrand Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> updateBrand(String accessToken, Long id, String name, MultipartFile file) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("id为空");
            }
            if (StringUtils.isBlank(name)) {
                return ResultBean.failedResultOfParamWithMsg("品牌名称为空");
            }

            Optional<SmartLockBrand> brandOpt = smartLockBrandRepository.findById(id);
            if (!brandOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁品牌不存在");
            }
            SmartLockBrand smartLockBrand = brandOpt.get();

            if (file != null) {
                // 上传图片
                ResultBean<Object> objectResultBean = ossService.putFile(ossConfig.getOssBucketName(), file, OSSUploadFileTypeEnum.LOGO.toString());
                String code = objectResultBean.getCode();
                String msg = objectResultBean.getMsg();
                if (!code.equals(StatusCode.SUCCESS_CODE_10000.getErrorCode())) {
                    return ResultBean.failedResultWithCodeAndMsg(code, msg);
                } else {
                    //删除logo
                    String logoPath = smartLockBrand.getLogoPath();
                    logoPath = logoPath.replace(ossConfig.getBucketUrl(), "");
                    ossService.deleteObject(ossConfig.getOssBucketName(), logoPath);

                    String fileKey = objectResultBean.getResultData().toString();
                    //String url = ossService.getOssFilePath(fileKey);
                    smartLockBrand.setName(name);
                    smartLockBrand.setLogoPath(fileKey);
                    smartLockBrand.setApiUrl(fileKey);
                    smartLockBrandRepository.save(smartLockBrand);
                }
            } else {
                smartLockBrand.setName(name);
                smartLockBrandRepository.save(smartLockBrand);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockBrandService updateBrand Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    @Transactional
    public ResultBean<Object> updateBrandStatus(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("品牌id为空");
            }
            Optional<SmartLockBrand> brandOpt = smartLockBrandRepository.findById(id);
            if (!brandOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁品牌不存在");
            }
            SmartLockBrand smartLockBrand = brandOpt.get();
            int status = smartLockBrand.getStatus();

            if (status == 0) {
                smartLockBrandRepository.updateStatus(id, 1);
            } else if (status == 1) {
                smartLockBrandRepository.updateStatus(id, 0);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockBrandService updateBrandStatus Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }


    @Transactional
    public ResultBean<Object> deleteBrand(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("品牌id为空");
            }

            smartLockBrandRepository.updateDelStatus(id, 2);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error("LockBrandService deleteLockBrand Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 查询品牌数据
     * @param accessToken
     * @param id
     * @return
     * @author shun
     * @date 2021年7月7日
     */
    public ResultBean<SmartLockBrand> getBrand(String accessToken, Long id) {
        try {
            if (id == null) {
                return ResultBean.failedResultOfParamWithMsg("id为空");
            }

            Optional<SmartLockBrand> brandOpt = smartLockBrandRepository.findById(id);
            if (!brandOpt.isPresent()) {
                return ResultBean.failedResultWithMsg("智能锁品牌不存在");
            }
            SmartLockBrand brand = brandOpt.get();
            brand.setSid(null);
            brand.setSercret(null);
            brand.setApiUrl(null);
            return ResultBean.successfulResult(brand);
        } catch (Exception e) {
            log.error("LockBrandService updateBrand Exception = {}" + e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }
}
